package com.guodi.model.utils;
import org.apache.any23.encoding.TikaEncodingDetector;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.filefilter.SuffixFileFilter;
import org.apache.commons.io.filefilter.TrueFileFilter;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;

import java.io.*;
import java.net.URLEncoder;

/**
* @描述: 文件分析工具类
* @作者: 代鹏刚
* @日期: 2023/3/8 14:45
**/
public class FileAnalysisUtils {
    public static TikaEncodingDetector tikaEncodingDetector = new TikaEncodingDetector();

    /**
    * @描述: 获取文件后缀
    * @入参:
    * @出参:
    * @作者: 代鹏刚
    * @日期: 2023/3/8 14:47
    **/
    public static String getFileFix(String fileName) {
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        return suffix;
    }

    /**
    * @描述: 源文件和视图文件异地存储
    * @入参:
    * @出参:
    * @作者: 代鹏刚
    * @日期: 2023/3/8 14:49
    **/
    public static String getOffSiteViewDir(String srcDir, String viewDir, String path, String viewFix) {
        if (StringUtils.isEmpty(viewFix)) {
            return path;
        }
        File source = new File(srcDir);
        File view = new File(viewDir);
        String p = replaceFirst(path, source.getPath(), view.getPath());
        return p + "." + viewFix;
    }

    public static String getFileSourceByView(String srcDir, String viewDir, String path) {
        File source = new File(srcDir);
        File view = new File(viewDir);
        String p = replaceFirst(path, view.getPath(), source.getPath());
        return p.substring(0, p.lastIndexOf("."));
    }

    /**
    * @描述: 字符串替换，左边第一个。
    * @入参:
    * @出参:
    * @作者: 代鹏刚
    * @日期: 2023/3/8 14:48
    **/
    public static String replaceFirst(String str, String oldStr, String newStr) {
        if (!newStr.endsWith(File.separator)) {
            newStr += File.separator;
        }
        if (!oldStr.endsWith(File.separator)) {
            oldStr += File.separator;
        }
        int i = str.indexOf(oldStr);
        if (i == -1) {
            return str;
        }
         str = str.substring(0, i) + newStr + str.substring(i + oldStr.length());

        return str;
    }

    /**
    * @描述: 将字符串中的中文进行编码
    * @入参:
    * @出参:
    * @作者: 代鹏刚
    * @日期: 2023/3/8 14:50
    **/
    public static String genIdByPath(String s) {
        char[] ch = s.toCharArray();
        String result = "";
        for (int i = 0; i < ch.length; i++) {
            char temp = ch[i];
            if (isChinese(temp)) {
                try {
                    String encode = URLEncoder.encode(String.valueOf(temp), "utf-8");
                    result = result + encode;
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            } else {
                result = result + temp;
            }
        }
        return result;
    }

    /**
    * @描述: 判断字符是否为汉字
    * @入参:
    * @出参:
    * @作者: 代鹏刚
    * @日期: 2023/3/8 14:50
    **/
    public static boolean isChinese(char c) {
        return c >= 0x4E00 && c <= 0x9FA5;
    }

    public static IOFileFilter getIOFileFilter(String[] supportExtensions) {
        IOFileFilter fileFilter;
        if (supportExtensions == null) {
            fileFilter = TrueFileFilter.INSTANCE;
        } else {
            String[] suffixes = toSuffixes(supportExtensions);
            fileFilter = new SuffixFileFilter(suffixes);
        }
        return fileFilter;
    }

    private static String[] toSuffixes(String[] extensions) {
        String[] suffixes = new String[extensions.length];

        for (int i = 0; i < extensions.length; ++i) {
            suffixes[i] = "." + extensions[i];
        }
        return suffixes;
    }

    public static String guessFileEncoding(InputStream inputStream) {
        return getCharsetDefault(inputStream);
    }

    public static File getResFile(String filename) throws FileNotFoundException {
        File file = new File(filename);
        if (!file.exists()) {
            file = new File("config/" + filename);
        }
        Resource resource = new FileSystemResource(file);
        if (!resource.exists()) {
            file = ResourceUtils.getFile("classpath:" + filename);
        }
        return file;
    }

    public static String getCharsetDefault(InputStream inputStream){
        BufferedInputStream bin=null;
        InputStream fileInputStream=null;
        try {
            //fileInputStream= new FileInputStream(file);
            bin = new BufferedInputStream(inputStream);
            String code= tikaEncodingDetector.guessEncoding(bin);
            new String(new byte[]{1,3,5,7},code);
            return tikaEncodingDetector.guessEncoding(bin);
        } catch (IOException e) {
            e.printStackTrace();
            return getCharset(inputStream);
        }
    }

    /**
    * @描述: 获得文件编码
    * @入参:
    * @出参:
    * @作者: 代鹏刚
    * @日期: 2023/3/8 14:50
    **/
    public static String getCharset(InputStream inputStream) {
        String code = "GBK";
        BufferedInputStream bin=null;
        //FileInputStream fileInputStream=null;
        try {
            //fileInputStream= new FileInputStream(file);
            bin = new BufferedInputStream(inputStream);
            int p = (bin.read() << 8) + bin.read();
            bin.close();
            switch (p) {
                case 0xefbb:
                    code = "UTF-8";
                    break;
                case 0xfffe:
                    code = "Unicode";
                    break;
                case 0xfeff:
                    code = "UTF-16BE";
                    break;
                default:{

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            IOUtils.closeQuietly(bin);
        }
        return code;
    }

    public static byte[] toByteArray(InputStream input) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[4096];
        int n = 0;
        while (-1 != (n = input.read(buffer))) {
            output.write(buffer, 0, n);
        }
        return output.toByteArray();
    }

    public static ByteArrayOutputStream cloneInputStream(InputStream input) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = input.read(buffer)) > -1) {
                baos.write(buffer, 0, len);
            }
            baos.flush();
            return baos;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

}
